package com.szh.eduservice.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.szh.eduservice.service.VodService;
import com.szh.eduservice.utils.ConstantVodUtils;
import com.szh.eduservice.utils.InitVodClient;
import com.szh.servicebase.exceptionhandler.GuliException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class VodServiceImpl implements VodService {

    //上传视频到阿里云
    @Override
    public String uploadAlyVideo(MultipartFile file) {
        try {
            //accessKeyId, accessKeySecret: id, 密钥 (参考OSS)
            //fileName: 上传文件的原始名称
            String fileName = file.getOriginalFilename();

            //title: 上传之后文件的名称
            String title = fileName.substring(0,fileName.lastIndexOf("."));

            //inputStream: 上传文件的输入流
            InputStream inputStream = file.getInputStream();

            //UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
            UploadStreamRequest request = new UploadStreamRequest(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET, title, fileName, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            String videoId = null;
            if (response.isSuccess()) {
                videoId = response.getVideoId();
            } else {
                videoId = response.getVideoId();
            }

            return videoId;
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据视频id删除阿里云视频
     * 服务降级
     * 超时访问，演示降级
     */
    @Override
    @HystrixCommand(fallbackMethod = "removeAlyVideoFallbackMethod",
                    commandProperties = {
                        @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")
                    })
    public void removeAlyVideo(String id) {
        try {
            //TimeUnit.SECONDS.sleep(5); 测试服务降级
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID,ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建删除视频的request、response对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            DeleteVideoResponse response = new DeleteVideoResponse();
            //将视频id存入request对象中
            request.setVideoIds(id);
            //调用初始化对象中的方法实现视频删除
            response = client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"删除视频失败");
        }
    }
    public void removeAlyVideoFallbackMethod(String id) {
        System.out.println("请求已超时, 此时已触发服务降级");
    }

    /**
     * 删除多个阿里云视频
     * 服务熔断
     */
    @Override
    @HystrixCommand(fallbackMethod = "removeMoreAlyVideoFallbackMethod",
                    commandProperties = {
                            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //是否开启断路器
                            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数
                            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //时间窗口期
                            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //失败率达到多少后跳闸
                    })
    public void removeMoreAlyVideo(List<String> videoIdList) {
        try {
            //int age = 10/0; 测试服务熔断
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID,ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建删除视频的request、response对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            DeleteVideoResponse response = new DeleteVideoResponse();
            //将videoIdList集合转为 1,2,3 格式
            String videoIds = StringUtils.join(videoIdList.toArray(), ",");
            //将多个视频id存入request对象中
            request.setVideoIds(videoIds);
            //调用初始化对象中的方法实现视频删除
            response = client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"删除多个视频失败");
        }
    }
    public void removeMoreAlyVideoFallbackMethod(List<String> videoIdList) {
        System.out.println("请求规则已打破, 此时已触发服务熔断");
    }
}
